package com.hejian.android.a72ggametools.asynctask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.hejian.android.a72ggametools.imageloader.ImageCache;
import com.hejian.android.a72ggametools.net.HttpUtils;

/**
 * Created by Administrator on 2016/1/11.
 */
public class DownloadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
    private Context context;
    private ImageCache imageCache;
    private ImageView imageView;
    private String urlStr;

    public DownloadImageAsyncTask(Context context, ImageCache imageCache, ImageView imageView) {
        this.context = context;
        this.imageCache = imageCache;
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        urlStr = params[0];
        Bitmap bitmap = downloadBitmap(urlStr);
        return bitmap;
    }

    private Bitmap downloadBitmap(String urlStr) {
        Bitmap bitmap = null;
        if (HttpUtils.isConnected(context)){
            byte[] buffer = HttpUtils.getNetWorkResult(urlStr);
            if (buffer != null && buffer.length>0){
                bitmap = BitmapFactory.decodeByteArray(buffer,0,buffer.length);
            }
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null){
            if (imageView.getTag().equals(urlStr)) {
                imageView.setImageBitmap(bitmap);
            }
            imageCache.setImage(urlStr,bitmap);
        }
    }
}
